package core;

import java.lang.annotation.Annotation;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.model.annotation.ExtractBy;

/**
 * Created by LouAnt on 2017/2/14 0014
 * Description：更新Openhub社区Homepage专用
 */
public class ModelPipeline4Update implements Pipeline{
    @SuppressWarnings("rawtypes")
    private Map<Class, PageModelPipeline4Update> pageModelPipelines = new ConcurrentHashMap<Class, PageModelPipeline4Update>();

    public ModelPipeline4Update() {
    }

    public ModelPipeline4Update put(Class<?> clazz,
                                    PageModelPipeline4Update<?> pageModelPipeline) {
        pageModelPipelines.put(clazz, pageModelPipeline);
        return this;
    }
    @SuppressWarnings({ "rawtypes", "unchecked", "deprecation" })
    public void process(ResultItems resultItems,Task task){}

    public void processUpdate(ResultItems resultItems,String url, Task task){
        for(Map.Entry<Class,PageModelPipeline4Update>classPageModelPipelineEntry : pageModelPipelines.entrySet()){
            boolean isSkip = resultItems.getFieldSkip(classPageModelPipelineEntry.getKey().getCanonicalName());
            if(isSkip)
                continue;

            Object o = resultItems.get(classPageModelPipelineEntry.getKey().getCanonicalName());

            if(o != null){
                Annotation annotation = classPageModelPipelineEntry.getKey().getAnnotation(ExtractBy.class);

                if(annotation == null || !((ExtractBy) annotation).multi()){
                    classPageModelPipelineEntry.getValue().processUpdate(o,url,task);
                }else{
                    List<Object> list = (List<Object>)o;
                    for(Object o1 : list){
                        classPageModelPipelineEntry.getValue().processUpdate(o1,url,task);
                    }
                }
            }
        }
    }
}
